<template>
  <div class="container">
    <!-- 卡片 -->
    <el-card class="box-card">
      <!-- 1-面包屑导航 导航问题-->
      <el-breadcrumb separator-class="el-icon-arrow-right"
      v-if="$route.query.id!=null">
        <el-breadcrumb-item>学科管理</el-breadcrumb-item>
        <el-breadcrumb-item>{{$route.query.name}}</el-breadcrumb-item>
        <el-breadcrumb-item>目录管理</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 2-form表单 搜索区域 -->
      <div>
        <el-form ref="form" label-width="80px">
          <el-row :gutter="20">
            <!-- 目录名 -->
            <el-col :span="6">
              <el-form-item label="目录名称">
                <el-input v-model.trim="queryInfo.directoryName"></el-input>
              </el-form-item>
            </el-col>
            <!-- 选择框 -->
            <el-col :span="6">
              <el-form-item label="状态">
                <el-select v-model="queryInfo.state" placeholder="请选择">
                  <el-option
                    v-for="item in options"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-button @click="clearBtn">清除</el-button>
              <el-button type="primary" @click="searchBtn">搜索</el-button>
            </el-col>
            <el-col :span="6">
              <div class="btn">
                <el-button
                  v-show="$route.query.id"
                  icon="el-icon-back"
                  class="back"
                  @click="$router.back()"
                  >返回学科</el-button
                >
                <el-button type="success" icon="el-icon-edit" @click="addDir"
                  >新增目录</el-button
                >
              </div>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!-- 2.提示 -->
      <el-alert
        :title="`数据一共${counts}条`"
        type="info"
        :closable="false"
        show-icon
      >
      </el-alert>

      <!-- 3-table数据区域 -->
      <el-table :data="dirList" style="width: 100%">
        <el-table-column type="index" label="序号" :index="rowIndex">
        </el-table-column>
        <el-table-column prop="subjectName" label="所属学科" width="180">
        </el-table-column>
        <el-table-column prop="directoryName" label="目录名称" width="180">
        </el-table-column>
        <el-table-column prop="username" label="创建者"> </el-table-column>
        <el-table-column prop="addDate" label="创建日期">
          <template slot-scope="scope">
            {{ scope.row.addDate | parseTimeByString }}
          </template>
        </el-table-column>
        <el-table-column prop="totals" label="面试题数量"> </el-table-column>
        <el-table-column prop="state" label="状态">
          <template slot-scope="scope">
            {{ scope.row.state === 1 ? "已启用" : "已禁用" }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              v-if="scope.row.state === 1"
              @click="stopById(scope.row)"
              >禁用</el-button
            >
            <el-button
              size="mini"
              type="text"
              v-else
              @click="stopById(scope.row)"
              >启用</el-button
            >
            <el-button size="mini"
            type="text"
             :disabled="scope.row.state === 1"
             @click="editDirById(scope.row)"
              >修改</el-button
            >
            <el-button size="mini" 
            type="text"
            :disabled="scope.row.state === 1"
            @click="deleteDirById(scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 4-分页 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page.sync="queryInfo.page"
        :page-sizes="[3, 5, 10, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="counts"
      >
      </el-pagination>
    </el-card>

    <!-- 5-新增目录区域 -->
    <el-dialog
      title="新增目录"
      :visible.sync="addDialogVisible"
      width="30%"
      @close="addDialogClose"
    >
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="所属学科"  v-if="$route.query.id==null" prop="subjectID">
          <el-select
            v-model="addForm.subjectID"
            placeholder="请选择"
            @clear="addDialogClose"
          >
            <el-option
              v-for="item in subInfo"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input v-model="addForm.directoryName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addDialog">确 定</el-button>
      </span>
    </el-dialog>

    <!--6- 修改目录弹层 -->
    <el-dialog
      title="修改目录"
      :visible.sync="editDialogVisible"
      width="30%"
      @close="editDialogClose"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="所属学科" v-if="$route.query.id==null">
          <el-select v-model="editForm.subjectID" placeholder="请选择">
            <el-option
              v-for="item in subInfo"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目录名称" prop="directoryName">
          <el-input v-model="editForm.directoryName"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editChange">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  list,
  detail,
  add,
  update,
  remove,
  changeState,
} from "@/api/hmmm/directorys";
import { simple as s } from "@/api/hmmm/subjects";
export default {
  name: "Directorys",
  data() {
    return {
      options: [
        {
          value: "1",
          label: "已启用",
        },
        {
          value: "0",
          label: "已禁用",
        },
      ],

      // 请求参数
      queryInfo: {
        directoryName: "", //目录名称
        page: 1, //当前页码数
        pagesize: 10, //当前每页显示的条数
        subjectID: null, //学科ID
        state: null, //状态 1 开启 0 屏蔽
      },
      counts: 1, //总记录数
      //获取到的目录数据列表
      dirList: [],

      // 控制新增目录弹层的显示与隐藏
      addDialogVisible: false,
      //新增目录表单对象
      addForm: {
        directoryName: "",
        subjectID: "",
      },
      //新增目录验证对象
      addFormRules: {
        directoryName: [
          { required: true, message: "请输入目录名称", trigger: "blur" },
        ],
       subjectID: [
          { required: true, message: "请选择所属学科", trigger: "change" },
        ],
      },
      //学科信息
      subInfo: [],

      // 修改目录
      editDialogVisible: false,
      //存储当前修改目录的详情--form表单数据源
      editForm: {
        directoryName: "",
        subjectID: "",
      },
      //修改表单的验证对象
      editFormRules: {
        directoryName: [
          { required: true, message: "请输入目录名称", trigger: "blur" },
        ],
      },
    };
  },
  computed: {
    //计算属性，解决切换页码值，索引初始化升序问题
    rowIndex() {
      //10, 第2页,11
      const beginIndex =
        (this.queryInfo.page - 1) * this.queryInfo.pagesize + 1;
      return beginIndex;
    },
  },

  created() {
    //初始化数据，调用请求目录列表
    this.getDirList();
    //发起请求，获取学科简单列表
    this.getSubjectList();
  },
  methods: {
    //1-请求获取目录数据列表
    async getDirList() {
      try {
        if (this.$route.query.id)
          this.queryInfo.subjectID = this.$route.query.id;
        else this.queryInfo.subjectID = null;
        const { data: res } = await list(this.queryInfo);
        console.log(res);
        //把获取到的目录数据列表存储到data
        this.dirList = res.items;
        this.counts = res.counts;
        console.log(this.dirList);
        // this.$message.success("获取目录数据列表成功");
      } catch (err) {
        console.log(err);
        this.$message.error("获取目录列表数据失败!");
      }
    },

    //2- 分页区域
    // 1 监听pagesize切换每页显示多少条数据变化，默认显示5条
    handleSizeChange(newpagesize) {
      this.queryInfo.pagesize = newpagesize;
      this.getDirList();
    },
    // 2 监听pagenum当前页码值变化,默认显示第1页
    handleCurrentChange(newpagenum) {
      this.queryInfo.page = newpagenum;
      this.getDirList();
    },
    //3-点击，清空搜索内容
    clearBtn() {
      this.queryInfo.directoryName = '';
      this.queryInfo.subjectID=null
      this.queryInfo.state =null;
      this.getDirList();
    },
    //4-点击搜索--------------------------------------------

    searchBtn() {
      if(this.queryInfo.directoryName ==='' && this.queryInfo.state==null){
        return this.$message.error('请输入搜索内容')
      }
      this.getDirList();
    },
    //5-点击，新增目录按钮弹框显示
    addDir() {
      this.addDialogVisible = true;
    },
    //监听弹层关闭事件，对新增表单重置
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
      this.subInfo.label = null;
    },
    //发起请求，获取学科简单列表
    async getSubjectList() {
      try {
        const { data: res } = await s();
        console.log(res);
        //把获取到的简单学科信息存储到data
        this.subInfo = res;
      } catch (err) {
        this.$message.error("获取学科简单列表失败!");
      }
    },

    //发起请求，添加新目录
    addDialog() {
      //对表单进行验证
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message("您的填写不符合");
        }
        try {
          //验证通过，发起请求新增目录---------------有问题-----------
          const { data: res } = await add({
            directoryName:this.addForm.directoryName,
            subjectID:this.addForm.subjectID
          });
          console.log(res);
          //成功提示
          this.$message.success('新增目录成功!')
          //更新页面
          this.getDirList()
        } catch (err) {
          this.$message.error("新增目录失败!");
        }
      });

      //关闭弹层
      this.addDialogVisible = false;
    },

    //---------编辑区域--------------
    //禁用与启用
    async stopById(row) {
      console.log(row.id);
      if (row.state === 1) {
        await changeState({
          id: row.id,
          state: "0",
        });
        this.getDirList();
        this.$message.success("更新当前目录状态成功");
      } else {
        await changeState({
          id: row.id,
          state: "1",
        });
        this.getDirList();
        this.$message.success("更新当前目录状态成功");
      }
    },

    //根据id修改目录
    async editDirById(row) {
      this.editDialogVisible = true;
      //先获取当前目录的详请
      try {
        const { data } = await detail({ id: row.id });
        console.log(data);
        //把获取到的当前目录信息存储到data--form表单
        this.editForm = data;
      } catch (err) {
        this.$message.error("获取目录详情失败！");
      }
    },
    //重置表单
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    //发起请求，更新目录
    editChange() {
      //对表单验证
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) {
          return this.$message("您的填写不符合");
        }
        try {
          const { data } = await update({
            id: this.editForm.id,
            subjectID: this.editForm.subjectID,
            directoryName: this.editForm.directoryName,
          });
          this.$message.success("修改目录成功!");
          this.getDirList();
          this.editDialogVisible = false;
        } catch (err) {
          console.log(err);
          this.$message.error("修改目录失败!");
        }
      });
    },

    // -----根据id删除当前目录--------------
    async deleteDirById(row) {
      console.log(row.id);
      //弹出MessageBox询问框，是否删除
      const confirmResult = await this.$confirm(
        "此操作将永久删除该目录, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => {
        return err;
      });
      //用户点击取消，得到字符串cancel
      //用户点击确定，得到字符串confirm
      console.log(confirmResult);
      //判断用户是否确定删除
      if (confirmResult !== "confirm") {
        return this.$message.info("已取消删除该目录！");
      }
      //发起请求，删除该目录
      try {
        const { data: res } = await remove({
          id: row.id,
        });
        // console.log(res);
        //更新页面
        this.getDirList();
        this.$message.success("成功删除该目录!");
      } catch (err) {
        this.$message.error("删除该目录失败!");
      }
     //当前页只有一条数据时，删除跳转
      if(this.dirList.length ===1 && this.queryInfo.page>1){
        this.queryInfo.page -=1 //向前跳一页
        this.getDirList()
      }
    },
  },
};
</script>

<style scoped lang='less'>
.btn {
  float: right;
}
.back {
  border: 0;
}
.el-pagination {
  float: right;
  margin-bottom: 15px;
}
.el-button {
  margin-right: 5px;
  cursor: pointer;
  // border:0
}
</style>